
import os
import zipfile
import datetime
# 测试压缩文件夹
def do_zip_compress(dirpath):
    print("start zipping, the file path is:" + dirpath)
    output_name = f"test.zip"
    parent_name = os.path.dirname(dirpath)
    # print("压缩文件夹目录：", parent_name)
    zip = zipfile.ZipFile(output_name, "w", zipfile.ZIP_DEFLATED)
    # 多层级压缩
    for root, dirs, files in os.walk(dirpath):
        for file in files:
            if str(file).startswith("~$"):
                continue
            filepath = os.path.join(root, file)
            print("压缩文件路径：" + filepath)
            writepath = os.path.relpath(filepath, parent_name)
            zip.write(filepath, writepath)
    zip.close()
    # print(output_name) # output_name是最终压缩文件夹的路径，这将会是传入参数dirpth后面加个.zip
    return output_name

def receiveZip(client):
    print(f"start receiving from client {client.id}")
    # now_time = time.strftime("%Y%m%d-%H%M%S")
    now_time = datetime.datetime.now().strftime('date%Y-%m-%d time%H_%M_%S')
    # now_time = now_time.replace(':','_')
    flie_name = f"{now_time}_id{client.id}.zip"
    #file = open(flie_name,"a",encoding=FORMAT) # w是只写模式，如果文件已存在则会先清空
    file = open(flie_name, "ab")

    while True:
        try:
            print("test point 1")
            total_data = b''
            data = client.socket.recv(1024)  # 执行这一句导致服务器异常关闭
            print(len(data))
            total_data += data
            file.write(total_data)
            # if not data:
            #     break
            while len(data) > 0:
                print(len(data))
                data = client.socket.recv(1024)
                total_data += data
                file.write(data)
            #file.write(total_data.decode(FORMAT))
            # file.write(total_data)
            break
        except Exception as e:
            print(repr(e))

    file.close()
    print(f"接收完成，文件名为{flie_name}")

if __name__ == '__main__':
    do_zip_compress("img")